package com.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class h039 {
    public static void main(String[] args) {
        int[] nums = {2,3,6,7};
        List<List<Integer>> list = combinationSum(nums, 7);
        list.forEach(item -> System.out.println(item));
    }

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        List<Integer> combine = new ArrayList<Integer>();
        dfs(candidates, target, ans, combine, 0);
        return ans;
    }

    public static void dfs(int[] nums, int target, List<List<Integer>> res, List<Integer> ans, int start) {
        if (target == 0){
            res.add(new ArrayList<>(ans));
            return;
        }

        for (int i=start;i<nums.length;i++){
            if (target - nums[i] < 0) return;

            if(i > 0&& nums[i] == nums[i-1]) continue;

            ans.add(nums[i]);
            //target -= nums[i];

            dfs(nums,target-nums[i],res,ans,i);

            ans.remove(ans.size()-1);
           // target +=nums[i];
        }
    }
}
